package org.lzy.shop.fragment

import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlinx.coroutines.launch
import org.lzy.shop.R
import org.lzy.shop.adapter.CommunityPostAdapter
import org.lzy.shop.base.BaseMvvmFragment
import org.lzy.shop.databinding.FragCommunityBinding
import org.lzy.shop.viewmodel.CommunityViewModel

/**
 * 社区/发现Fragment
 */
class CommunityFragment : BaseMvvmFragment<FragCommunityBinding, CommunityViewModel>(FragCommunityBinding::inflate), SwipeRefreshLayout.OnRefreshListener {

    private var hasMoreData: Boolean=true
    private var isLoading: Boolean=false
    private val communityPostAdapter: CommunityPostAdapter by lazy { CommunityPostAdapter() }
    private var currentPage = 1
    private val pageSize = 10

    override fun initView() {
        // 设置RecyclerView
        binding.rvPosts.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = communityPostAdapter
        }

        // 设置刷新监听器
        binding.refreshLayout.setOnRefreshListener {
            currentPage = 1
            if (binding.tabRecommend.isSelected) {
                loadCommunityPosts()
            } else {
                loadFollowPosts()
            }
        }

        // 设置Tab切换
        setupTabs()

        // 设置监听事件
        setupListeners()
    }

    override fun requestData() {
        loadCommunityPosts()
    }

    override fun initData() {
        observeCommunityPosts()
    }

    override fun allClick() {

    }

    /**
     * 设置Tab切换
     */
    private fun setupTabs() {
        // 设置默认选中推荐
        binding.tabRecommend.isSelected = true
        binding.tabFollow.isSelected = false

        binding.tabRecommend.setOnClickListener {
            binding.tabRecommend.isSelected = true
            binding.tabFollow.isSelected = false
            // 加载推荐内容
            currentPage = 1
            loadCommunityPosts()
        }

        binding.tabFollow.setOnClickListener {
            binding.tabRecommend.isSelected = false
            binding.tabFollow.isSelected = true
            // 加载关注内容
            currentPage = 1
            loadFollowPosts()
        }
    }

    /**
     * 设置监听事件
     */
    private fun setupListeners() {
        // 点击发帖按钮
        binding.btnCreatePost.setOnClickListener {
            // 跳转到发帖页面（待实现）
            showToast(getString(R.string.create_post_tip))
        }

        // 帖子点击事件
        communityPostAdapter.setOnItemClickListener { _, _, position ->
            // 跳转到帖子详情页（待实现）
            showToast(getString(R.string.view_post_detail))
        }

        // 点赞按钮点击事件
        communityPostAdapter.setOnLikeClickListener { position ->
            toggleLike(position)
        }

        // 评论按钮点击事件
        communityPostAdapter.setOnCommentClickListener { position ->
            // 跳转到评论页面（待实现）
            showToast(getString(R.string.view_comments))
        }
    }

    /**
     * 加载社区帖子
     */
    private fun loadCommunityPosts() {
        lifecycleScope.launch {
            mViewModel.getCommunityPosts(currentPage, pageSize)
        }
    }

    /**
     * 加载关注的帖子
     */
    private fun loadFollowPosts() {
        lifecycleScope.launch {
            mViewModel.getFollowPosts(currentPage, pageSize)
        }
    }

    /**
     * 观察社区帖子数据
     */
    private fun observeCommunityPosts() {
        mViewModel.communityPostsLiveData.observeWithLifecycle(viewLifecycleOwner) { posts ->
            // 停止刷新动画和加载状态
            finishRefresh()
            isLoading = false

            if (posts != null) {
                if (posts.isNotEmpty()) {
                    if (currentPage == 1) {
                        communityPostAdapter.submitList(posts)
                    } else {
                        communityPostAdapter.appendList(posts)
                    }
                    // 设置有更多数据
                    hasMoreData = true
                } else {
                    // 没有更多数据了
                    if (currentPage > 1) {
                        hasMoreData = false
                        // 可以在这里显示"没有更多数据"的提示
                    }
                }
            }
        }

        mViewModel.errorLiveData.observeWithLifecycle(viewLifecycleOwner) { errorMsg ->
            // 停止刷新动画和加载状态
            finishRefresh()
            isLoading = false

            if (!errorMsg.isNullOrEmpty()) {
                showToast(errorMsg)
            }
        }
    }

    private fun finishRefresh() {
        binding.refreshLayout.isRefreshing = false
    }

    /**
     * 切换点赞状态
     */
    private fun toggleLike(position: Int) {
        val post = communityPostAdapter.getItem(position)
        post?.let {
            lifecycleScope.launch {
                val isLiked = !it.isLiked
                mViewModel.toggleLike(post.id, isLiked)
                // 本地更新点赞状态
                it.isLiked = isLiked
                it.likeCount += if (isLiked) 1 else -1
                communityPostAdapter.notifyItemChanged(position)
            }
        }
    }

    override fun onRefresh() {

    }
}